const express = require('express')
const mysql = require('mysql')
const db = mysql.createPool({
  host: 'localhost',
  user: 'root',
  password: '123456789',
  database: 'learner'
})
// title, summary, ico_src, big_pic_src, content
module.exports = function () {
  let router = express.Router()

  router.get('/', (req, res) => {
    db.query(`SELECT * FROM news_table`, (err, news) => {
      if (err) {
        console.error(err)
        res.status(500).send('database error').end()
      } else {
        res.render('admin/news.ejs', { news })
      }
    })
  })

  router.post('/', (req, res) => {
    let title = req.body.title
    let summary = req.body.summary
    let ico_src = req.body.ico_src
    let big_pic_src = req.body.big_pic_src
    let content = req.body.content
    db.query(`INSERT INTO news_table (title, summary, ico_src, big_pic_src, content) VALUE('${title}', '${summary}', '${ico_src}', '${big_pic_src}', '${content}')`, (err, data) => {
      if (err) {
        console.error(err)
        res.status(500).send('database error').end()
      } else {
        res.redirect('/admin/news')
      }
    })
  })

  return router
}
